<!-- MessageForm.vue -->
<template>
    <div style="height: auto;">
        <form @submit.prevent="handleSubmit" class="message-form">
            <textarea v-model="messageText" placeholder="请输入您的留言..." rows="2" required maxlength="4096" show-word-limit
                class="message-input"></textarea>
            <button type="submit" :disabled="!messageText.trim()" class="submit-button">
                发布
            </button>
        </form>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useStore } from 'vuex';
import { commitCourseForumMessageApi } from '@/api/course'
import { ElMessage } from 'element-plus';
const props = defineProps({
    course_id: {
        type: Number,
        required: true,
    }
})
const messageText = ref('');
const store = useStore()
async function handleSubmit() {
    if (!messageText.value.trim()) return;

    try {
        // 发送新的聊天消息到服务器
        commitCourseForumMessageApi({
            user_id: store.state.user.user_id,
            is_teacher: store.state.user.is_teacher,
            course_id: props.course_id,
            message: messageText.value.trim()
        }).then((res:any) => {
            if (res.code === 200) { 
                ElMessage.success({
                    message: '留言成功！',
                    type:'success'
                });
                location.reload();
            }
            else {
                ElMessage.error({
                    message: '留言失败，请稍后再试！',
                    type: 'error'
                });
            }
        })
        messageText.value = '';
    } catch (error) {
        console.error('Failed to submit message:', error);
    }
}

</script>

<style scoped>
.message-form {
    display: flex;
    flex-direction: column;
    margin-bottom: 1rem;
}

.message-input {
    width: 100%;
    box-sizing: border-box;
    padding: 0.5rem;
    font-size: 1rem;
    resize: vertical;
    border: 1px solid #ced4da;
    border-radius: 0.25rem;
}

.submit-button {
    width: 100%;
    padding: 0.5rem;
    font-size: 1rem;
    background-color: #0d6efd;
    color: #fff;
    border: none;
    border-radius: 0.25rem;
    cursor: pointer;
    transition: background-color 0.2s ease-in-out;

    &:hover {
        background-color: #0b5ed7;
    }

    &[disabled] {
        background-color: #ccc;
        cursor: not-allowed;
    }
}
</style>